package com.zenkeeuk.bookcamera.client.android;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import com.zenkeeuk.bookcamera.client.android.Contents.GET_BOOK_MSG;
import com.zenkeeuk.bookcamera.client.android.book.DoubanBookInfo;
import com.zenkeeuk.bookcamera.client.android.history.HistoryManager;
import com.zenkeeuk.bookcamera.client.android.http.HttpUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class BookDetailActivity extends Activity {

	private ProgressDialog myDialog = null;
	private String message;
	private Contents.GET_BOOK_MSG getbookStatus = GET_BOOK_MSG.ERROR;
	private String isbn = null;
	private boolean iscompare = false;
	
	private DoubanBookInfo doubanInfo = null;
	
	@Override
	public void onCreate(Bundle icicle) {
	    super.onCreate(icicle);
	    requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.bookdetail);	    
	    myDialog = ProgressDialog.show(this, "查询图书信息", "查询图书信息中，请稍等...", true);
		
	    isbn = this.getIntent().getStringExtra(Contents.INTENT_EXTRA_ISBN_KEY);
        iscompare = this.getIntent().getBooleanExtra(Contents.INTENT_EXTRA_ISCOMPARE_KEY, false);
	    if (isbn != null || isbn.trim().equals("")){
	    	new Thread(getBookInfo).start();
	    } else {
	    	myDialog.dismiss();
	    	Toast.makeText(getApplicationContext(), "未查询到此书！", Toast.LENGTH_SHORT).show();
	    	this.finish();
	    }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    super.onCreateOptionsMenu(menu);
	    menu.add(0, Contents.HOME_ID, 0, R.string.menu_home)
	        .setIcon(R.drawable.homebtn);
	    menu.add(0, Contents.HISTORY_ID, 0, R.string.menu_history)
	        .setIcon(R.drawable.historybtn);
	    menu.add(0, Contents.SETTINGS_ID, 0, R.string.menu_settings)
	        .setIcon(R.drawable.settingbtn);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case Contents.HOME_ID: {
	        	Intent intent = new Intent(Intent.ACTION_VIEW);
		        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		        intent.setClassName(this, HomePageActivity.class.getName());
		        startActivity(intent);
		        break;
	        }
	        case Contents.HISTORY_ID: {
		    	Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			    intent.setClassName(this, HomePageActivity.class.getName());
			    intent.putExtra(Contents.INTENT_EXTRA_RETURN_TO_TAP_KEY, 1);
			    startActivity(intent);
			    break;
		    }
	        case Contents.SETTINGS_ID: {
	        	Intent intent = new Intent(Intent.ACTION_VIEW);
			    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			    intent.setClassName(this, HomePageActivity.class.getName());
			    intent.putExtra(Contents.INTENT_EXTRA_RETURN_TO_TAP_KEY, 2);
			    startActivity(intent);
			    break;
	        }
	    }
	    return super.onOptionsItemSelected(item);
	}
	
	public Runnable getBookInfo = new Runnable() {
		public void run() {
			if(isbn!=null){
				try{
					doubanInfo = HistoryManager.getBookItem(isbn, getBaseContext());
					if(doubanInfo == null) {
						// 获取豆瓣书信息
						String url = String.format(Contents.GET_BOOK_BASEINFO_URL_TEMPLETE_JSON, isbn);
			        	JSONObject obj = HttpUtil.getJsonData(url);
			        	
			        	if (obj == null) {
			        		message = "查询信息失败";
			        		getbookStatus = GET_BOOK_MSG.ERROR;
			        	} else {
			        		doubanInfo = HistoryManager.updateBookDoubanInfo(isbn, obj, getBaseContext());

							String fileName = isbn + ".jpeg";
							String bigCoverfile = isbn + ".PNG";
			        		HttpUtil httpUtil = new HttpUtil();
							httpUtil.getUrlImage(fileName, doubanInfo.getImgicohref(), Bitmap.CompressFormat.JPEG);
							httpUtil.getUrlImage(bigCoverfile, doubanInfo.getImghsrc(), Bitmap.CompressFormat.PNG);
					        message = "查询信息成功";
					        getbookStatus = GET_BOOK_MSG.OK;
			        	}
					} else {
						message = "查询信息成功";
						getbookStatus = GET_BOOK_MSG.OK;
					}
				} catch (Exception e) {
					message = "查询信息失败";
					getbookStatus = GET_BOOK_MSG.ERROR;
				}
				messageHandler.sendMessage(messageHandler.obtainMessage());
			}
		}
	};
	
	private Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	myDialog.dismiss();
        	Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            /*final AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
            builder.setMessage(message);
            
            builder.setIcon(android.R.drawable.ic_dialog_info);
            builder.create().show();*/
            
        	switch(getbookStatus){
        		case OK:
        			TextView isbn_text = (TextView)findViewById(R.id.isbn_detail);
                    TextView book_title = (TextView)findViewById(R.id.book_title);
                    TextView book_authors = (TextView)findViewById(R.id.author_detail);
                    TextView book_press = (TextView)findViewById(R.id.press_detail);
                    TextView book_rating = (TextView)findViewById(R.id.rating_detail);
                    TextView price_detail = (TextView)findViewById(R.id.price_detail);
                    RatingBar book_ratingBar = (RatingBar)findViewById(R.id.book_ratingBar);
                    TextView book_description = (TextView)findViewById(R.id.summary_detail);
                    ImageView bookcover = (ImageView)findViewById(R.id.book_cover);
                    
                    // 设置view大小
                    //DisplayMetrics dm = new DisplayMetrics();
                    //getWindowManager().getDefaultDisplay().getMetrics(dm);
                    //int maxWidth = (int) ((dm.widthPixels > dm.heightPixels ? dm.heightPixels : dm.widthPixels) * 0.4);
                    //int maxHeight = (int) (maxWidth * Contents.BOOK_COVER_ASPECT_RATIO);
                    //bookcover.setMaxWidth(maxWidth);
                    //bookcover.setMaxHeight(maxHeight);
                    
                    // 绑定view 内容
                    isbn_text.setText(isbn);
                    book_title.setText(doubanInfo.getBookName());
                    book_authors.setText(doubanInfo.getAuthors());
                    book_press.setText(doubanInfo.getPress());
                    if (doubanInfo.getRating() != 0) {
                    	book_rating.setText(String.valueOf(doubanInfo.getRating()));
                    } else {
                    	book_rating.setText(Contents.DOUBAN_NO_RATING);
                    } 
                    book_ratingBar.setMax(10);
                    book_ratingBar.setRating((float) doubanInfo.getRating());
                    price_detail.setText(doubanInfo.getPrice());
                    book_description.setText(doubanInfo.getDescription());
                    
                    Bitmap bm = BitmapFactory.decodeFile(Contents.DOUBAN_IMG_FOLDER_PATH + isbn + ".jpeg");	    
                    bookcover.setImageBitmap(bm);
                    
                    ImageButton book_comments = (ImageButton)findViewById(R.id.book_comments);
                    ImageButton book_share = (ImageButton)findViewById(R.id.book_share);
                    ImageButton book_compare = (ImageButton)findViewById(R.id.book_compare);
                    
                    
                    
                    // 绑定按钮事件                    
                    book_comments.setOnClickListener(new Button.OnClickListener(){
            			public void onClick(View v) {
            				Intent intent = new Intent(getBaseContext(), BookCommentsActivity.class);
            				intent.putExtra(Contents.INTENT_EXTRA_ISBN_KEY, isbn);
            				intent.putExtra(Contents.INTENT_EXTRA_BOOK_NAME, doubanInfo.getBookName());
            				startActivity(intent);
            			}
            		});
                    
                    book_share.setOnClickListener(new Button.OnClickListener(){
            			public void onClick(View v) {
            			    Intent intent = new Intent(Intent.ACTION_SEND);
            			    intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name) + " - 分享图书");
            			    intent.putExtra(Intent.EXTRA_TEXT, "给大家分享一本书——《" + doubanInfo.getBookName() + "》    来自布客");
            			    
            			    String bigCoverfile = Contents.DOUBAN_IMG_FOLDER_PATH + isbn + ".PNG";
            			    File coverFile = new File(bigCoverfile);
        				    if(!coverFile.exists()){
								try {
									URL url = new URL(doubanInfo.getImghsrc());
		            	            HttpURLConnection conn  = (HttpURLConnection)url.openConnection();
		            	            conn.setDoInput(true);
		            	            conn.connect();
		            	            InputStream inputStream = conn.getInputStream();
		            	            Bitmap bitmap = BitmapFactory.decodeStream(inputStream); 
		            	            
		            	            // 保存图片
		            	            String status = Environment.getExternalStorageState();
		            				if (status.equals(Environment.MEDIA_MOUNTED)) { // 有插入SD卡
		            					File dirFile = new File(Contents.DOUBAN_IMG_FOLDER_PATH);
		            				    if(!dirFile.exists()){
		            				    	dirFile.mkdir();
		            				    }
		            				    File myCaptureFile = new File(bigCoverfile);
		            				    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
		            				    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
		            				    bos.flush();
		            				    bos.close();
		            				} else {
		            					//TODO: 没有插入SD卡
		            				}
								} catch (Exception e) {
									Toast.makeText(getApplicationContext(), "获取封面图片失败！", Toast.LENGTH_SHORT).show();
								}
        				    }
							intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + bigCoverfile));
            			    intent.setType("image/jpg");
            			    //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            			    startActivity(Intent.createChooser(intent, null));
            			}
            		});
                    
                    if (iscompare) {
                    	book_compare.setVisibility(View.GONE);
                    } else {
	                    book_compare.setOnClickListener(new Button.OnClickListener(){
	            			public void onClick(View v) {
	            				Intent intent = new Intent(getBaseContext(), BookComparisonActivity.class);
	            				intent.putExtra(Contents.INTENT_EXTRA_ISBN_KEY, isbn);            				
	            				startActivity(intent);
	            			}
	            		});
                    }
                    
        			break;
        		case ERROR:
        			Toast.makeText(getApplicationContext(), "未查询到此书！", Toast.LENGTH_SHORT).show();
        	    	
        			finish();
        			break;
        	}
        }
	};
	
}
